import AliyunOSSUpload from '@/components/AliyunOSSUpload';
import { add_edit_video, get_video_info } from '@/services/assrssment';
import { filedlist } from '@/services/platformuser';
import { get_acceass } from '@/utils/Aliyun_oss';
import { UploadOutlined } from '@ant-design/icons';
import {
  ActionType,
  ProColumns,
  ProForm,
  ProFormGroup,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Divider, message, Modal, Spin, Table, Upload } from 'antd';
import { RcFile } from 'antd/es/upload';
import moment from 'moment';
import { useEffect, useState } from 'react';

interface Iprops {
  isShowEditVideoModal: (show: boolean) => void;
  editVideoModal: boolean;
  actionRef: React.MutableRefObject<ActionType | undefined>;
  videoId: number | undefined;
}
type GithubIssueItem = {
  video_name: string;
  id: number;
  video_times: number;
  size: number;
  video_time: number;
  video_size: number;
  plan_time: string;
  end_time: string;
  create_at: string;
  create_user: string;
};
var videname = '';
var sizes = '0';
const EditMyselfVideo = (props: Iprops) => {
  const { isShowEditVideoModal, editVideoModal, actionRef, videoId } = props;
  // 个人信息
  const { initialState } = useModel('@@initialState');
  // 上传状态
  const [uploading, setuploading] = useState(false);
  // 视频时长
  const [video_time, setvideo_time] = useState(0);
  const [disable, setdisable] = useState(false);
  // 图片地址
  const [imageUrl, setimageUrl] = useState('');
  // 视频列表数据
  const [videodata, setvideodata] = useState<any>(undefined);
  const [filelist, setfilelist] = useState<any>([{}]);
  // 视频地址
  const [videourl, setvideourl] = useState();

  // 页面初始化，获取视频详情
  useEffect(() => {
    const getData = async () => {
      if (videoId) {
        let res: any = await get_video_info({ id: videoId });
        console.log('视频详情', res);
        if (res.code === 200) {
          let file: any = [];
          let fileinfo: any = {};
          // video_name  文件名称  video_time 视频时长  size 文件大小 platform_user_name 上传人   upload_time 上传时间
          fileinfo['id'] = res.data.id;
          fileinfo['video_name'] = res.data.video_name;
          fileinfo['video_time'] = res.data.video_time;
          fileinfo['video_size'] = res.data.video_size;
          fileinfo['platform_user_name'] = res.data.platform_user_name;
          fileinfo['create_time'] = res.data.create_time;
          file.push(fileinfo);
          setvideodata(res.data);
          setfilelist(file);
          setimageUrl(res.data.icon);
        }
      }
    };
    getData();
  }, []);

  // 删除视频
  const Delvideo = () => {
    setdisable(false);
    setfilelist([{}]);
    setvideo_time(0);
  };

  // 图片删除
  const del = () => {
    setimageUrl('');
  };

  // 获取视频分类
  const get_field = async (key: string) => {
    let request_body = {
      type: key,
    };
    let params = await filedlist(request_body);
    // console.log(params);
    let res: any = [];
    params.data.map((item: any) => {
      let temp: any = {};
      temp['label'] = item.value;
      temp['value'] = parseInt(item.key);
      res.push(temp);
    });
    return res;
  };

  //获取oss服务端签名
  const send_request = async (info: any) => {
    let res = await get_acceass(info);
    doUploadFile(res.ossHost, res.glo_image_data, res.filePath);
  };

  // 视频大小转换
  function sizeTostr(size: number) {
    //转化MB
    var data = (size / (1024 * 1024)).toFixed(2);
    var len = data.indexOf('.');
    var dec = data.substring(len + 1, 2);
    if (dec == '00') {
      //当小数点后为00时 去掉小数部分
      return data.substring(0, len) + data.substring(len + 3, 2);
    }
    return data;
  }

  function doUploadFile(
    url: string,
    data: { [x: string]: string | Blob; file: any },
    filePath: any,
  ) {
    setuploading(true);
    setdisable(true);

    var oMyForm = new FormData();
    for (var field_name in data) {
      oMyForm.append(field_name, data[field_name]);
    }
    var oReq = new XMLHttpRequest();
    oReq.onreadystatechange = function (e) {
      if (oReq.readyState == 4) {
        if (oReq.status == 200) {
          setvideourl(filePath);
          // 获取视频时长
          var audio = new Audio(filePath);
          audio.addEventListener('loadedmetadata', function (e) {
            setvideo_time(Math.round(audio.duration));
          });
          var myDate = new Date();
          let create_time = myDate.toLocaleTimeString();
          let fileinfo = data.file;
          let file = [];
          let temp: any = {};
          // video_name  文件名称  video_times 视频时长  size 文件大小 name 上传人   upload_time 上传时间
          temp['video_name'] = fileinfo.name;
          temp['video_size'] = sizeTostr(fileinfo.size);
          temp['platform_user_name'] = initialState?.currentUser?.username;
          temp['create_time'] = create_time;
          file.push(temp);
          setfilelist(file);
          setuploading(false);
          setdisable(false);
        }
      }
    };
    oReq.open('POST', url);
    // 在这里提交数据到oss
    oReq.send(oMyForm);
  }

  // 上传验证
  const beforeUpload = (file: RcFile) => {
    const filetype = file.type === 'video/mp4';
    if (!filetype) {
      message.error('只能上传mp4文件');
    }
    return filetype;
  };

  // 编辑提交
  const edit_video = async (value: any) => {
    let request_body = {
      ...value,
      id: videoId,
      video_name: filelist[0].video_name,
      video_size: filelist[0].video_size,
      video_time: video_time ? video_time : videodata.video_time,
      url: videourl ? videourl : videodata.url,
      icon: imageUrl,
    };
    console.log(request_body);
    let res: any = await add_edit_video(request_body);
    console.log('编辑视频', res);
    if (res.code === 200) {
      //刷新列表
      actionRef.current?.reload();
      message.success('编辑成功');
      //关闭弹窗
      isShowEditVideoModal(false);
    } else {
      message.error(res.msg);
    }
  };

  // 视频文件列表字段
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: '文件名称',
      hideInSearch: true,
      key: 'video_name',
      dataIndex: 'video_name',
    },
    {
      title: '视频时长',
      hideInSearch: true,
      key: 'video_time',
      dataIndex: 'video_time',
      render: (_, record) => {
        var x = 0;
        if (record.video_time) {
          x = record.video_time;
        } else {
          if (video_time != 0) {
            x = video_time;
          } else {
            return;
          }
        }
        var d = moment.duration(x, 'seconds');
        var hours: any = Math.floor(d.asHours()).toString();
        var mins: any = (Math.floor(d.asMinutes()) - hours * 60).toString();
        var second = (Math.floor(d.asSeconds()) - mins * 60).toString();
        if (hours.toString().length == 1) {
          hours = '0' + hours;
        }
        if (mins.toString().length == 1) {
          mins = '0' + mins;
        }
        if (second.toString().length == 1) {
          second = '0' + second;
        }
        return hours + ':' + mins + ':' + second;
      },
    },
    {
      title: '文件大小',
      hideInSearch: true,
      align: 'center',
      key: 'video_size',
      dataIndex: 'video_size',
      render: (_, record) => {
        if (record.video_size) {
          let text = '';
          text += record.video_size + 'MB';
          return text;
        }
      },
    },
    {
      title: '上传人',
      hideInSearch: true,
      key: 'platform_user_name',
      dataIndex: 'platform_user_name',
    },
    {
      title: '上传时间',
      hideInSearch: true,
      key: 'create_time',
      dataIndex: 'create_time',
    },
    {
      title: '操作',
      hideInSearch: true,
      key: 'action',
      align: 'center',
      render: (_, record) => {
        if (record.video_name) {
          return (
            <a key="Del" onClick={Delvideo}>
              删除
            </a>
          );
        } else {
          return (
            <Upload
              name="head_img"
              className="avatar-uploader"
              beforeUpload={(info) => beforeUpload(info)}
              customRequest={(info) => send_request(info)}
              showUploadList={false}
            >
              <Button disabled={disable} loading={uploading} icon={<UploadOutlined />}>
                上传
              </Button>
            </Upload>
          );
        }
      },
    },
  ];
  return (
    <Modal
      title="编辑视频"
      centered
      open={editVideoModal}
      onCancel={() => isShowEditVideoModal(false)}
      width={800}
      destroyOnClose={true}
      footer={null}
    >
      <Divider />
      {videodata === undefined ? (
        <div
          style={{
            margin: '20px 0',
            marginBottom: '20px',
            padding: '30px 50px',
            textAlign: 'center',
          }}
        >
          <Spin size="large" />
        </div>
      ) : (
        <>
          {' '}
          <ProForm
            submitter={{
              searchConfig: {
                submitText: '提交',
                resetText: '取消',
              },
              resetButtonProps: {
                style: {
                  // 隐藏重置按钮
                  display: 'block',
                  position: 'absolute',
                  left: 'calc(50% - 107px)',
                },
              },
              submitButtonProps: {
                style: {
                  display: 'block',
                  position: 'absolute',
                  right: 'calc(50% - 107px)',
                },
              },
            }}
            onReset={() => isShowEditVideoModal(false)}
            onFinish={(value) => edit_video(value)}
          >
            <div>
              <ProFormGroup>
                <div style={{ display: 'flex', width: '280px' }}>
                  <div className="ant-col ant-form-item-label" style={{ width: '80px' }}>
                    <label className="ant-form-item-required" title="评估分类">
                      视频图片
                    </label>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <AliyunOSSUpload
                      imageUrl={imageUrl}
                      setImageUrl={setimageUrl}
                    ></AliyunOSSUpload>
                    <Button style={{ marginLeft: '20px' }} onClick={del}>
                      删除
                    </Button>
                  </div>
                </div>
                <ProFormText
                  width={280}
                  style={{ marginLeft: '15px' }}
                  name="name"
                  label="视频名称"
                  placeholder="视频名称"
                  rules={[
                    {
                      required: true,
                      message: '请输入视频名称',
                    },
                    { pattern: /(^\S)((.)*\S)?(\S*$)/, message: '不能输入空格' },
                  ]}
                  initialValue={videodata.name}
                />
                <ProFormSelect
                  width={280}
                  name="cate_type"
                  label="评估分类"
                  request={async () => [{ label: '脑卒中', value: 1 }]}
                  rules={[
                    {
                      required: true,
                      message: '请输入评估分类',
                    },
                  ]}
                  initialValue={videodata.cate_type}
                />
                <ProFormSelect
                  name="type"
                  label="视频分类"
                  width={280}
                  request={async () => get_field('video_type')}
                  rules={[
                    {
                      required: true,
                      message: '请输入视频分类',
                    },
                  ]}
                  initialValue={videodata.type}
                />
                <ProFormText
                  width={592}
                  name="remark"
                  label="备注"
                  placeholder="请输入备注"
                  rules={[
                    {
                      max: 300,
                      message: '备注最多300 字符',
                      validateTrigger: 'onBlur',
                    },
                  ]}
                  initialValue={videodata.remark}
                />
              </ProFormGroup>
            </div>

            <div className="ant-col ant-form-item-label" style={{ width: '100px' }}>
              <label className="ant-form-item-required" title="评估分类">
                视频文件
              </label>
            </div>
            <Table
              columns={columns}
              dataSource={filelist}
              rowKey={(record) => (record.id ? record.id : 0)}
              pagination={false}
              style={{ paddingBottom: '20px' }}
            />
            <br />
          </ProForm>
        </>
      )}

      <br />
    </Modal>
  );
};
export default EditMyselfVideo;
